import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';

class CustomImageSwiper extends StatefulWidget {
  final List<String> imageList;
  const CustomImageSwiper({super.key, required this.imageList});

  @override
  State<CustomImageSwiper> createState() => _CustomImageSwiperState();
}

class _CustomImageSwiperState extends State<CustomImageSwiper> {
  int _current = 0;
  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _scrollController.addListener(_onScroll);
  }

  void _onScroll() {
    // 计算当前显示的图片索引
    double offset = _scrollController.offset;
    double itemExtent = 250.w + 5.w; // 图片宽+右间隔
    int index = (offset / itemExtent).round();
    if (index != _current && index >= 0 && index < widget.imageList.length) {
      setState(() {
        _current = index;
      });
    }
  }

  @override
  void dispose() {
    _scrollController.removeListener(_onScroll);
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        SizedBox(
          height: 320.w,
          child: ListView.builder(
            controller: _scrollController,
            scrollDirection: Axis.horizontal,
            itemCount: widget.imageList.length,
            itemBuilder: (context, index) {
              return Padding(
                padding: EdgeInsets.only(
                  left: index == 0 ? 19.w : 5.w,
                  right: 5.w,
                ),
                child: GestureDetector(
                  onTap: () {
                    setState(() {
                      // _current = index;
                    });
                  },
                  child: SizedBox(
                    width: 250.w,
                    height: 320.w,
                    child: ClipRRect(
                      borderRadius: BorderRadius.circular(12),
                      child: Image.asset(
                        widget.imageList[index],
                        fit: BoxFit.cover,
                      ),
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        const SizedBox(height: 16),
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: List.generate(widget.imageList.length, (index) {
            return Container(
              margin: const EdgeInsets.symmetric(horizontal: 4),
              width: _current == index ? 10.w : 4.w,
              height: 4.h,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2.5).r,
                color: _current == index
                    ? Colors.white
                    : Color(0XFFD9D9D9).withAlpha(127),
              ),
            );
          }),
        ),
      ],
    );
  }
}
